package beer.xz.beer.device.util

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.provider.Settings
import android.util.Log
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import beer.xz.beer.device.util.ShellUtil.execCommand
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.common.BitMatrix
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object Utils {

    fun generateQRCode(data: String, size: Int): ImageBitmap {
        val bitMatrix: BitMatrix =
            MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, size, size)
        val width = bitMatrix.width
        val height = bitMatrix.height
        val pixels = IntArray(width * height)

        for (y in 0 until height) {
            val offset = y * width
            for (x in 0 until width) {
                pixels[offset + x] = if (bitMatrix.get(x, y)) Color.BLACK else Color.WHITE
            }
        }

        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
        return bitmap.asImageBitmap()
    }


    @SuppressLint("HardwareIds")
    fun getControllerCode(context: Context): String? {
        var result: String?
        result = getWifiMacAddress() ?: ""
        Log.d("getControllerCode", "wifi mac: $result")
        if (result.isEmpty()) {
            result = getCpuId() ?: ""
            Log.d("getControllerCode", "cup id: $result")
        }
        if (result.isEmpty()) {
            result = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
            Log.d("getControllerCode", "android id: $result")
        }
        return result?.md5()
    }


    //    /**
//     * Get WiFi MAC address
//     *
//     * @return WiFi MAC address or null if not found
//     */
//    fun getWifiMacAddress(): String? {
//        val command = "iwconfig wlan0 | grep 'HWaddr' | awk '{print $5}'"
//        val commandResult = execCommand(command, false, true)
//        if (commandResult.result == 0 && commandResult.successMsg != null) {
//            return commandResult.successMsg!!.trim()
//        }
//        return null
//    }
    @SuppressLint("MissingPermission")
    fun getWifiMacAddress(): String? {
        val command = "cat /sys/class/net/wlan0/address"
        val commandResult = execCommand(command, true, true) // Use root command
        if (commandResult.result == 0 && commandResult.successMsg != null) {
            return commandResult.successMsg!!.trim()
        }
        return null
    }

    /**
     * Get CPU ID
     *
     * @return CPU ID or null if not found
     */
    fun getCpuId(): String? {
        val command = "cat /proc/cpuinfo | grep 'Serial' | awk '{print $3}'"
        val commandResult = execCommand(command, false, true)
        // Check if the command was successful and the result is not null
        if (commandResult.result == 0 && commandResult.successMsg != null) {
            return commandResult.successMsg!!.trim()
        }
        // Return null if the CPU ID could not be retrieved
        return null
    }
}

fun String.md5(): String {
    return try {
        val md = MessageDigest.getInstance("MD5")
        val digest = md.digest(toByteArray())
        digest.fold("") { str, it -> str + "%02x".format(it) }
    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
        throw RuntimeException("MD5 algorithm not found")
    }
}